package grpc

import (
	"context"
	"fmt"
	"gitlab.local/backend/proto/manager"
	"manager/bll"
	log "manager/collector/logger"
	"manager/model"
	"manager/store/postgres"
	"manager/utils"
)

type Manager struct {
}

// GetAlarmTypeList 获取告警信息
func (m *Manager) GetAlarmTypeList(ctx context.Context, in *manager.GetAlarmTypeListReq, out *manager.GetAlarmTypeListRsp) (err error) {
	fmt.Println("---- grpc GetAlarmTypeList data:", utils.ToJsonString(in))
	// 警告类型列表请求
	total, list, err := postgres.AlarmType.ListByIds(ctx, &model.AlarmTypeExtraListRequest{
		Index: 1,
		Size:  -1,
		Ids:   in.AlarmTypeIds,
	})
	if err != nil {
		log.Errorf("ManagerService GetAlarmTypeInfo err:%v ", err)
		return
	}

	*out = manager.GetAlarmTypeListRsp{
		Total: int32(total),
	}

	for i := 0; i < len(list); i++ {
		out.List = append(out.List, &manager.AlarmTypeInfo{
			Id:      list[i].Id,
			Name:    list[i].Name,
			Content: list[i].Content,
			Low:     int32(list[i].Low),
			High:    int32(list[i].High),
		})
	}
	return
}

// GetAlarmList 获取告警信息
func (m *Manager) GetAlarmList(ctx context.Context, in *manager.GetAlarmListReq, out *manager.GetAlarmListRsp) (err error) {
	fmt.Println("---- grpc GetAlarmList data:", utils.ToJsonString(in))
	req := &model.AlarmListRequest{}
	value := int(in.Index)
	req.Index = value
	value = int(in.Size)
	req.Size = value

	if in.Level > 0 {
		value = int(in.Level)
		req.Level = &value
	}

	if in.UserId > 0 {
		req.UserId = &in.UserId
	}

	if in.Type > 0 {
		req.Type = &in.Type
	}

	if in.EbikeId > 0 {
		req.EbikeId = &in.EbikeId
	}

	if in.EbikeTypeId > 0 {
		req.EbikeTypeId = &in.EbikeTypeId
	}

	rsp, err := bll.Alarm.List(ctx, req)
	if err != nil {
		log.Errorf("ManagerService GetAlarmList err:%v ", err)
		return
	}

	*out = manager.GetAlarmListRsp{
		Total: int32(rsp.Total),
	}

	for i := 0; i < len(rsp.List); i++ {
		out.List = append(out.List, &manager.AlarmInfo{
			Id:            rsp.List[i].Id,
			UserId:        rsp.List[i].UserId,
			EbikeId:       rsp.List[i].EbikeId,
			AlarmTypeId:   rsp.List[i].Type,
			EbikeTypeId:   rsp.List[i].EbikeTypeId,
			EbikeTypeName: rsp.List[i].EbikeTypeName,
			Level:         int32(rsp.List[i].Level),
			Score:         int32(rsp.List[i].Score),
			CreatedAt:     rsp.List[i].CreatedAt,
		})
	}
	return
}
